package id.co.rho.scoring.cid.client.mvc.login;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.KeyListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.widget.Info;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;

import id.co.rho.scoring.cid.client.command.CommandDispatcherAsync;
import id.co.rho.scoring.cid.client.command.impl.LoginCommandAction;
import id.co.rho.scoring.cid.client.command.impl.LoginCommandResult;
import id.co.rho.scoring.cid.client.managed.request.ApplicationRequestFactory;
import id.co.rho.scoring.cid.client.mvc.AppEvents;
import id.co.rho.scoring.cid.client.mvc.AppView;
import id.co.rho.scoring.cid.client.security.CredentialConfigurer;
import id.co.rho.scoring.cid.client.utils.NavigationMenuUtils;

import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: frizky
 * Date: 10/17/11
 * Time: 1:02 PM
 */
public class LoginView extends View {

    private ApplicationRequestFactory requestFactory;
    private LoginUI loginUI;
    private CommandDispatcherAsync dispatcher;
    private CredentialConfigurer  credential;
    private NavigationMenuUtils menuUtil;
    private AppView appView;

    /**
     * Creates a new view instance.
     */
    @Inject
    public LoginView(ApplicationRequestFactory requestFactory, 
                     LoginUI loginUI, CommandDispatcherAsync dispatcher,
                     CredentialConfigurer  credential,
                     AppView appView) {
        super(null);
        this.requestFactory = requestFactory;
        this.loginUI = loginUI;
        this.dispatcher = dispatcher;
        this.credential = credential;
        controller = new ViewController();
        this.menuUtil = new NavigationMenuUtils();
        this.appView = appView;
    }

    @Override
    protected void initialize() {
        super.initialize();
        loginUI.initialize();
        loginUI.getUserName().addKeyListener(keyListener);
        loginUI.getPassField().addKeyListener(keyListener);
        
        loginUI.getBtnLogin().addSelectionListener(new SelectionListener<ButtonEvent>() {
            @Override
            public void componentSelected(ButtonEvent ce) {
            	doLogin();
            }
        });
    }
    
    public void doLogin(){
    	if(loginUI.getPassFieldValue()==null || loginUI.getPassFieldValue().trim().isEmpty()){
    		Info.display("Login", "Login Failed. Please input password");
    		loginUI.getPassField().focus();
    	}else{
	    	LoginCommandAction action = new LoginCommandAction(LoginCommandAction.TYPE.LOGIN, loginUI.getUserNameValue(), loginUI.getPassFieldValue(), null);
	        dispatcher.execute(action, new AsyncCallback<LoginCommandResult>() {
	            @Override
	            public void onFailure(Throwable caught) {
	                throw new RuntimeException(caught);
	            }
	
	            @Override
	            public void onSuccess(LoginCommandResult result) {
	                if (result != null && result.getCredential() != null) {
	                    final long DURATION = 1000 * 60 * 60 * 24 * 1;
	                    Date expires = new Date(System.currentTimeMillis() + DURATION);
	                    Cookies.setCookie("xms", result.getStringCockie(), expires, null, "/", false);
	                    credential.setId(result.getCredential().getId());
	                    credential.setUserId(result.getCredential().getUserId());
	                    credential.setUsername(result.getCredential().getUsername());
	                    credential.setListRole(result.getCredential().getListRole());
	
	                    Dispatcher.forwardEvent(AppEvents.LoginSuccess);
	                    Info.display("Login", "Login "+ result.getCredential().getUsername()+ " Success.");
	                }else if(result != null && result.getCredential() == null){
	                	Info.display("Login", "Login Failed. "+result.getMessage());
	                }                
	            }
	        });
    	}
    }
    
    @Override
    protected void handleEvent(AppEvent event) {
    	appView.getUserName().setText("");
        loginUI.attach();
        loginUI.show();
        loginUI.getUserName().focus();
        String xms = Cookies.getCookie("xms");
        LoginCommandAction action = new LoginCommandAction(LoginCommandAction.TYPE.LOGOUT);
        action.setStringCockie(xms);
        dispatcher.execute(action, new AsyncCallback<LoginCommandResult>() {
            @Override
            public void onFailure(Throwable caught) {
            }
            @Override
            public void onSuccess(LoginCommandResult result) {
            }
        });
        Cookies.removeCookie("xms");
    }

    private class ViewController extends Controller {
        public ViewController() {
            registerEventTypes(AppEvents.MainLoginView);
        }

        @Override
        public void handleEvent(AppEvent event) {
            forwardToView(LoginView.this, event);
        }
    }
    
    KeyListener keyListener = new KeyListener() {
        public void componentKeyUp(ComponentEvent event) {
        	if(event.getKeyCode() == 13){ //if press enter key
        		doLogin();
        	}
        }
    };
}
